<template>
  <view class="pad30">
    <view class="flex-align flex-between form-item">
      <view>头像</view>
      <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <image class="avatar" :src="userInfo.avatar || defaultAvatarUrl"></image>
      </button>
    </view>
    <view class="flex-align flex-between form-item" style="border-top: 1px solid #eee">
      <text>昵称</text>
      <input v-model="userInfo.userName" type="nickname" class="weui-input" placeholder="请输入昵称" />
    </view>
    <view class="flex-align flex-between form-item" style="border-top: 1px solid #eee">
      <text>性别</text>
      <picker mode="selector" :value="sexIdx" :range="['男', '女']" @change="bindPickerChange">
        {{ userInfo.gender ? userInfo.gender : '请选择' }}
      </picker>
    </view>
    <view class="mt100">
      <button type="primary" @tap="submit">确定</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import homeApi from '@/api/homeApi'

const defaultAvatarUrl =
  'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const avatar = ref(defaultAvatarUrl)
const onChooseAvatar = (e: any) => {
  const { avatarUrl } = e.detail
  avatar.value = avatarUrl
}

onLoad((e: any) => {
  getUserInfo()
})
const sexIdx = ref(-1)
const bindPickerChange = (e: any) => {
  console.log(e.detail.value)
  sexIdx.value = e.detail.value
  if (sexIdx.value == 0) {
    userInfo.value.gender = '男'
  } else if (sexIdx.value == 1) {
    userInfo.value.gender = '女'
  }
}
const userInfo = ref()
const getUserInfo = () => {
  homeApi
    .getUserInfo({
      userId: uni.getStorageSync('userId'),
    })
    .then((res: any) => {
      userInfo.value = res.data
      userInfo.value.userId = uni.getStorageSync('userId')
    })
}

const submit = () => {
  homeApi.updateUserInfo(userInfo.value).then((res: any) => {
    if (res.success) {
      uni.showToast({
        title: '修改成功',
        icon: 'success',
        duration: 2000,
      })
    }
  })
}
</script>
<style lang="scss" scoped>
button {
  color: #fff;
  background-color: $uni-color-primary;
  border: none;
}
.avatar-wrapper {
  padding: 0;
  position: absolute;
  right: 0;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  .avatar {
    width: 100rpx;
    height: 100rpx;
  }
}
.weui-input {
  text-align: right;
}
.form-item {
  position: relative;
  height: 120rpx;
  display: flex;
  align-items: center;
}
</style>
